<template>
  <div class="user-management-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateUser">
          <el-icon><Plus /></el-icon>新建用户
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="用户名">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="filterForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="filterForm.roleId" placeholder="请选择角色" clearable>
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 用户表格 -->
    <div class="user-table">
      <el-table
        :data="displayUserList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="roleName" label="角色" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="230">
          <template #default="scope">
            <el-button size="small" @click="handleEditUser(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'" 
              @click="handleToggleStatus(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="info"
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDeleteUser(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑用户对话框 -->
    <el-dialog
      v-model="userDialog.visible"
      :title="userDialog.isEdit ? '编辑用户' : '新建用户'"
      width="600px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username" :disabled="userDialog.isEdit">
          <el-input 
            v-model="userForm.username" 
            placeholder="请输入用户名" 
            :disabled="userDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userDialog.isEdit">
          <el-input 
            v-model="userForm.password" 
            placeholder="请输入密码" 
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 重置密码结果对话框 -->
    <el-dialog
      v-model="resetPasswordDialog.visible"
      title="重置密码成功"
      width="400px"
    >
      <div class="reset-password-result">
        <p>新密码已生成，请妥善保管并及时通知用户更改</p>
        <div class="new-password">
          <span>新密码：</span>
          <el-tag size="large">{{ resetPasswordDialog.newPassword }}</el-tag>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="resetPasswordDialog.visible = false">确定</el-button>
        <el-button type="info" @click="copyPassword">复制密码</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

export default {
  name: 'UserManagement',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 模拟角色数据
    const roleList = [
      { id: 1, name: '超级管理员', code: 'SUPER_ADMIN' },
      { id: 2, name: '管理员', code: 'ADMIN' },
      { id: 3, name: '窗口操作员', code: 'OPERATOR' },
      { id: 4, name: '统计分析员', code: 'ANALYST' }
    ]
    
    // 模拟用户数据
    const mockUsers = [
      {
        id: 1,
        username: 'admin',
        name: '系统管理员',
        roleId: 1,
        roleName: '超级管理员',
        phone: '13900000001',
        email: 'admin@example.com',
        status: 1,
        lastLoginTime: '2023-06-10 08:30:45',
        createTime: '2023-01-01 00:00:00'
      },
      {
        id: 2,
        username: 'zhangsan',
        name: '张三',
        roleId: 2,
        roleName: '管理员',
        phone: '13900000002',
        email: 'zhangsan@example.com',
        status: 1,
        lastLoginTime: '2023-06-09 17:22:10',
        createTime: '2023-01-02 10:15:30'
      },
      {
        id: 3,
        username: 'lisi',
        name: '李四',
        roleId: 3,
        roleName: '窗口操作员',
        phone: '13900000003',
        email: 'lisi@example.com',
        status: 1,
        lastLoginTime: '2023-06-10 09:05:12',
        createTime: '2023-01-03 14:30:00'
      },
      {
        id: 4,
        username: 'wangwu',
        name: '王五',
        roleId: 3,
        roleName: '窗口操作员',
        phone: '13900000004',
        email: 'wangwu@example.com',
        status: 1,
        lastLoginTime: '2023-06-09 16:45:38',
        createTime: '2023-01-04 09:20:15'
      },
      {
        id: 5,
        username: 'zhaoliu',
        name: '赵六',
        roleId: 4,
        roleName: '统计分析员',
        phone: '13900000005',
        email: 'zhaoliu@example.com',
        status: 0,
        lastLoginTime: '2023-05-30 10:20:33',
        createTime: '2023-01-05 15:10:25'
      }
    ]
    
    // 用户列表数据
    const userList = ref([...mockUsers])
    const tableLoading = ref(false)
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: mockUsers.length
    })
    
    // 过滤表单
    const filterForm = reactive({
      username: '',
      name: '',
      roleId: '',
      status: ''
    })
    
    // 用户对话框
    const userDialog = reactive({
      visible: false,
      isEdit: false
    })
    
    // 重置密码对话框
    const resetPasswordDialog = reactive({
      visible: false,
      newPassword: ''
    })
    
    // 用户表单
    const userFormRef = ref(null)
    const userForm = reactive({
      id: null,
      username: '',
      name: '',
      roleId: '',
      phone: '',
      email: '',
      password: '',
      status: 1
    })
    
    // 表单验证规则
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      roleId: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 获取已注册用户列表
    const getRegisteredUsers = () => {
      const usersStr = localStorage.getItem('registeredUsers')
      return usersStr ? JSON.parse(usersStr) : []
    }
    
    // 保存用户列表到localStorage
    const saveRegisteredUsers = (users) => {
      localStorage.setItem('registeredUsers', JSON.stringify(users))
    }
    
    // 加载所有用户（包括注册用户）
    const loadAllUsers = () => {
      tableLoading.value = true
      
      // 获取注册用户
      const registeredUsers = getRegisteredUsers()
      
      // 合并用户列表
      userList.value = [
        ...mockUsers,
        ...registeredUsers
      ]
      
      pagination.total = userList.value.length
      tableLoading.value = false
    }
    
    // 根据筛选条件和分页显示用户列表
    const displayUserList = computed(() => {
      // 应用筛选条件
      let filteredList = userList.value.filter(item => {
        let usernameMatch = true, nameMatch = true, roleMatch = true, statusMatch = true
        
        if (filterForm.username) {
          usernameMatch = item.username.includes(filterForm.username)
        }
        
        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }
        
        if (filterForm.roleId) {
          roleMatch = item.roleId === filterForm.roleId
        }
        
        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }
        
        return usernameMatch && nameMatch && roleMatch && statusMatch
      })
      
      // 应用分页
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      
      return filteredList.slice(start, end)
    })
    
    // 监听筛选列表变化更新总数
    const updatePaginationTotal = () => {
      const filteredList = userList.value.filter(item => {
        let usernameMatch = true, nameMatch = true, roleMatch = true, statusMatch = true
        
        if (filterForm.username) {
          usernameMatch = item.username.includes(filterForm.username)
        }
        
        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }
        
        if (filterForm.roleId) {
          roleMatch = item.roleId === filterForm.roleId
        }
        
        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }
        
        return usernameMatch && nameMatch && roleMatch && statusMatch
      })
      
      pagination.total = filteredList.length
    }
    
    // 监听过滤条件变化
    watch([() => filterForm.username, () => filterForm.name, () => filterForm.roleId, () => filterForm.status], () => {
      updatePaginationTotal()
    })
    
    // 监听用户列表变化
    watch(userList, () => {
      updatePaginationTotal()
    }, { deep: true })
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
    }
    
    // 重置过滤器
    const resetFilter = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = ''
      })
      pagination.currentPage = 1
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }
    
    // 处理刷新
    const handleRefresh = () => {
      tableLoading.value = true
      setTimeout(() => {
        tableLoading.value = false
        ElMessage.success('刷新成功')
      }, 500)
    }
    
    // 处理新建用户
    const handleCreateUser = () => {
      userDialog.isEdit = false
      userDialog.visible = true
      
      Object.keys(userForm).forEach(key => {
        if (key === 'status') {
          userForm[key] = 1
        } else {
          userForm[key] = ''
        }
      })
    }
    
    // 处理编辑用户
    const handleEditUser = (row) => {
      userDialog.isEdit = true
      userDialog.visible = true
      
      userForm.id = row.id
      userForm.username = row.username
      userForm.name = row.name
      userForm.roleId = row.roleId
      userForm.phone = row.phone
      userForm.email = row.email
      userForm.status = row.status
    }
    
    // 处理切换用户状态
    const handleToggleStatus = (row) => {
      // 禁止修改内置用户
      if (['superadmin', 'admin', 'operator'].includes(row.username)) {
        ElMessage.warning('系统内置用户不允许修改状态')
        return
      }
      
      const statusText = row.status === 1 ? '禁用' : '启用'
      
      ElMessageBox.confirm(`确定要${statusText}用户"${row.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 查找用户
        const index = userList.value.findIndex(user => user.id === row.id)
        if (index > -1) {
          // 修改用户状态
          userList.value[index].status = row.status === 1 ? 0 : 1
          
          // 如果是注册用户，需要更新localStorage
          const registeredUsers = getRegisteredUsers()
          const registeredIndex = registeredUsers.findIndex(user => user.id === row.id)
          
          if (registeredIndex > -1) {
            registeredUsers[registeredIndex].status = userList.value[index].status
            saveRegisteredUsers(registeredUsers)
          }
          
          ElMessage.success(`${statusText}用户成功`)
        }
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 处理删除用户
    const handleDeleteUser = (row) => {
      // 禁止删除内置用户
      if (['superadmin', 'admin', 'operator'].includes(row.username)) {
        ElMessage.warning('系统内置用户不允许删除')
        return
      }
      
      ElMessageBox.confirm(`确定要删除用户"${row.name}"吗？此操作不可恢复！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        // 从用户列表中删除
        userList.value = userList.value.filter(user => user.id !== row.id)
        
        // 如果是注册用户，需要从localStorage中删除
        const registeredUsers = getRegisteredUsers()
        const filteredUsers = registeredUsers.filter(user => user.id !== row.id)
        
        if (filteredUsers.length !== registeredUsers.length) {
          saveRegisteredUsers(filteredUsers)
        }
        
        pagination.total = userList.value.length
        ElMessage.success('删除用户成功')
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 处理重置密码
    const handleResetPassword = (row) => {
      ElMessageBox.confirm(`确定要重置用户"${row.name}"的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 生成随机密码
        const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
        let password = ''
        for (let i = 0; i < 8; i++) {
          password += chars.charAt(Math.floor(Math.random() * chars.length))
        }
        
        // 显示重置密码对话框
        resetPasswordDialog.newPassword = password
        resetPasswordDialog.visible = true
        
        // 在实际应用中，这里应该调用API将新密码保存到数据库
      }).catch(() => {})
    }
    
    // 复制密码
    const copyPassword = () => {
      const input = document.createElement('input')
      input.value = resetPasswordDialog.newPassword
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      ElMessage.success('密码已复制到剪贴板')
    }
    
    // 提交用户表单
    const submitUserForm = () => {
      userFormRef.value.validate((valid) => {
        if (valid) {
          const isEdit = userDialog.isEdit
          
          if (isEdit) {
            // 编辑现有用户
            const index = userList.value.findIndex(item => item.id === userForm.id)
            if (index !== -1) {
              // 获取角色名称
              const role = roleList.find(r => r.id === userForm.roleId)
              const roleName = role ? role.name : ''
              
              userList.value[index] = {
                ...userList.value[index],
                name: userForm.name,
                roleId: userForm.roleId,
                roleName: roleName,
                phone: userForm.phone,
                email: userForm.email,
                status: userForm.status,
              }
              
              // 如果是注册用户，需要更新localStorage
              const registeredUsers = getRegisteredUsers()
              const registeredIndex = registeredUsers.findIndex(user => user.id === userForm.id)
              
              if (registeredIndex > -1) {
                registeredUsers[registeredIndex] = {
                  ...registeredUsers[registeredIndex],
                  name: userForm.name,
                  roleId: userForm.roleId,
                  roleName: roleName,
                  phone: userForm.phone,
                  email: userForm.email,
                  status: userForm.status,
                }
                saveRegisteredUsers(registeredUsers)
              }
              
              ElMessage.success('更新用户成功')
            }
          } else {
            // 创建新用户
            const role = roleList.find(r => r.id === userForm.roleId)
            const roleName = role ? role.name : ''
            
            const newUser = {
              id: Date.now(),
              username: userForm.username,
              name: userForm.name,
              roleId: userForm.roleId,
              roleName: roleName,
              phone: userForm.phone,
              email: userForm.email,
              password: userForm.password,
              status: userForm.status,
              lastLoginTime: null,
              createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
            }
            
            userList.value.push(newUser)
            
            // 如果是普通用户（窗口操作员），也添加到注册用户列表
            if (userForm.roleId === 3) {
              const registeredUsers = getRegisteredUsers()
              registeredUsers.push(newUser)
              saveRegisteredUsers(registeredUsers)
            }
            
            pagination.total = userList.value.length
            ElMessage.success('创建用户成功')
          }
          
          userDialog.visible = false
        }
      })
    }
    
    // 初始化加载
    onMounted(() => {
      loadAllUsers()
    })
    
    return {
      roleList,
      displayUserList,
      tableLoading,
      pagination,
      filterForm,
      userDialog,
      userFormRef,
      userForm,
      userRules,
      resetPasswordDialog,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateUser,
      handleEditUser,
      handleDeleteUser,
      handleToggleStatus,
      handleResetPassword,
      copyPassword,
      submitUserForm
    }
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.user-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.reset-password-result {
  padding: 20px;
  text-align: center;
}

.new-password {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-password span {
  margin-right: 10px;
}
</style> 